<template>
	<view class="downLoadCode" v-show="loading == false">
		<image class="codeImg" lazy-load :src="base64" mode="aspectFit" />
		<view class="btn" @click="clickBtn()" v-show="loading == false">下载收款码</view>
		<loading v-if="loading"></loading>
	</view>
</template>

<script>
const app = getApp()
export default {
	data() {
		return {
			base64: '', //base64格式图片
			loading: false,
		}
	},

	created() {
		this.getImgUrl()
	},

	methods: {
		//获取二维码图片
		getImgUrl() {
			this.loading = true;
			let _this = this;
			app.get('ApiStore/getposter', {}, function (res) {
				_this.base64 = res.replace(/[\r\n]/g, "");
				_this.loading = false;
			});
		},

		clickBtn() {
			//获取用户的当前设置
			uni.getSetting({
				success: (res) => {
					if (res.authSetting['scope.writePhotosAlbum']) {
						//验证用户是否授权可以访问相册
						this.saveImageToPhotosAlbum();
					} else {
						//如果没有授权，向用户发起请求
						uni.authorize({
							scope: 'scope.writePhotosAlbum',
							success: () => {
								this.saveImageToPhotosAlbum();
							},
							fail: () => {
								uni.showToast({
									title: "请打开保存相册权限，再点击下载收款码！",
									icon: "none",
									duration: 2000
								});
								setTimeout(() => {
									uni.openSetting({ //调起客户端小程序设置界面,让用户开启访问相册
										success: (setRes) => {
											console.log(setRes.authSetting)
										}
									});
								}, 2000);
							}
						})
					}
				}
			})
		},

		saveImageToPhotosAlbum() {
			this.loading = true;
			let base64 = this.base64.replace(/^data:image\/\w+;base64,/, "");
			let filePath = wx.env.USER_DATA_PATH + '/qrcode.png';
			uni.getFileSystemManager().writeFile({
				filePath: filePath, //创建一个临时文件名
				data: base64, //写入的文本或二进制数据
				encoding: 'base64', //写入当前文件的字符编码
				success: (res) => {
					uni.saveImageToPhotosAlbum({
						filePath: filePath,
						success: () => {
							uni.showToast({
								title: '图片以保存至手机相册，请前往手机相册查看！',
								icon: "none",
								duration: 5000
							})
							this.loading = false;
						},
						fail: (err) => {
							console.log(err);
							this.loading = false;
						}
					})
				},
				fail: (err) => {
					console.log(err)
					this.loading = false;
				}
			})
		}
	}
}
</script>

<style lang="scss">
.downLoadCode {
	width: 100vw;
	height: 100vh;
	background: #ffbe4a;
}

.codeImg {
	width: 100%;
	height: 100%;
}

.btn {
	width: 90%;
	position: fixed;
	left: 5%;
	bottom: 30rpx;
	line-height: 90rpx;
	border-radius: 15rpx;
	text-align: center;
	font-weight: bold;
	font-size: 28rpx;
	color: #fff;
	letter-spacing: 1px;
	background: #FD4A46;
}
</style>